package com.ezjie.ielts.module_read;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.constant.Constants;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.core.http.ServerInterfaceDefinition;
import com.ezjie.ielts.core.spfs.SharedPrefHelper;
import com.ezjie.ielts.db.ExamListInfoDB;
import com.ezjie.ielts.db.SubjectInfoDB;
import com.ezjie.ielts.db.UserInfoDB;
import com.ezjie.ielts.model.ExamListDetail;
import com.ezjie.ielts.model.ExamListInfo;
import com.ezjie.ielts.model.SubjectDetail;
import com.ezjie.ielts.model.SubjectInfo;
import com.ezjie.ielts.module_read.adapter.ExamAdapter;
import com.ezjie.ielts.module_read.adapter.ReadExamExpandAdapter;
import com.ezjie.ielts.task.ReadBooksTask;
import com.ezjie.ielts.task.ReadSubjectsTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.widget.TitleTextView;
import com.ezjie.login.LoginActivity;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

@ContentView(R.layout.activity_read_exam)
public class ReadExamActivity extends BaseFragmentActivity {

	@ViewInject(R.id.iv_topbar_back)
	private ImageView iv_topbar_back;
	@ViewInject(R.id.iv_topbar_right)
	private ImageView iv_topbar_right;
	@ViewInject(R.id.tv_topbar_title)
	private TitleTextView tv_topbar_title;
	@ViewInject(R.id.lv_read_exam)
	private ListView listView;
	private ExamAdapter adapter;
	private List<ExamListDetail> examDatas = new ArrayList<ExamListDetail>();
	private List<ExamListDetail> sortDatas = new ArrayList<ExamListDetail>();
	private List<SubjectDetail> subjectDatas = new ArrayList<SubjectDetail>();

	private ExamListInfoDB examListDb;
	private SubjectInfoDB subjectDb;

	private UserInfoDB userInfoDB;

	private PopupWindow mPopupWindow;
	private ExpandableListView mExpandableListView;
	private ReadExamExpandAdapter mExamExpandAdapter;

	private Context mContext;
	private ReadSubjectsTask rSubjectsTask;
	private ReadBooksTask rBooksTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);

		rSubjectsTask = new ReadSubjectsTask(this);
		rBooksTask = new ReadBooksTask(this);
		examListDb = new ExamListInfoDB(this);
		subjectDb = new SubjectInfoDB(this);
		userInfoDB = new UserInfoDB(this);

		mContext = this;
		init();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_READ_EXAM);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_READ_EXAM);
	}

	private void init() {
		tv_topbar_title.setText(R.string.exam_practice);
		iv_topbar_back.setOnClickListener(this);
		iv_topbar_right.setVisibility(View.VISIBLE);
		iv_topbar_right.setOnClickListener(this);

		adapter = new ExamAdapter(mContext);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (userInfoDB.queryLoginUser().islogin == 0) {
					startActivity(new Intent(mContext, LoginActivity.class));
					return;
				}
				// 友盟统计
				MobclickAgent.onEvent(mContext, "readExam_listItemClick");
				Intent intent = new Intent(ReadExamActivity.this, ReadAllPracticeActivity.class);
				intent.putExtra(Constants.READ_ID, adapter.getItem(position).category_id);
				intent.putExtra(Constants.READ_FROM, Constants.READ_FROM_VALUE2);
				startActivity(intent);
			}
		});
		initPopupWindow();

		if (SharedPrefHelper.getInstance().getUpdatetime(ServerInterfaceDefinition.READ_BOOKS)
				&& NetworkUtil.isNetworkAvailable(mContext)) {
			getBooksTask();
			SharedPrefHelper.getInstance().setUpdatetime(ServerInterfaceDefinition.READ_BOOKS);
		} else {
			examDatas = examListDb.query(ExamListDetail.READ);
			adapter.resetData(examDatas);
			subjectDatas = subjectDb.query(1);
			mExamExpandAdapter.reset(subjectDatas);
		}
	}

	private void getBooksTask() {
		rBooksTask.doGetBooks(new HttpRequestAbstractCallBack(mContext,false) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				// AppUtil.dismissProgressDialog();
				LogUtils.d(result);
				ExamListInfo info = JSON.parseObject(result, ExamListInfo.class);
				examDatas = info.getData();
				for (int i = 0; i < examDatas.size(); i++) {
					examDatas.get(i).type = ExamListDetail.READ;
				}

				adapter.resetData(examDatas);

				getSubjectsTask();

				// 更新数据库
				examListDb.replaceInto(examDatas);
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
			}
		});
	}

	private void getSubjectsTask() {
		rSubjectsTask.doGetSubject(new HttpRequestAbstractCallBack(mContext,false) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				// AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				SubjectInfo info = JSON.parseObject(result, SubjectInfo.class);
				subjectDatas = info.getData();

				for (int j = 0; j < subjectDatas.size(); j++) {
					subjectDatas.get(j).type = ExamListDetail.READ;
					int x = 0;
					for (int i = 0; i < examDatas.size(); i++) {
						if (examDatas.get(i).classify_id.equals(subjectDatas.get(j).classify_id)) {
							x += 1;
							subjectDatas.get(j).num = x;
						}
					}
				}

				mExamExpandAdapter.reset(subjectDatas);
				AppUtil.dismissProgressDialog();

				// 更新数据库
				subjectDb.replaceInto(subjectDatas);
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
			}
		});
	}

	private void initPopupWindow() {
		View view = LayoutInflater.from(mContext).inflate(R.layout.popup_exam_filter, null);
		// 设置View的最大高度
		mPopupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		// 需要设置一下此参数，点击外边可消失
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击窗口外边窗口消失
		mPopupWindow.setOutsideTouchable(true);
		// 设置此参数获得焦点，否则无法点击
		mPopupWindow.setFocusable(true);

		mExamExpandAdapter = new ReadExamExpandAdapter(mContext);
		mExpandableListView = (ExpandableListView) view.findViewById(R.id.elv_fiter);
		View empty_view1 = view.findViewById(R.id.v1_empty);
		View empty_view2 = view.findViewById(R.id.v2_empty);
		empty_view1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mPopupWindow != null && mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
				}
			}
		});
		empty_view2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mPopupWindow != null && mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
				}
			}
		});
		mExpandableListView.setGroupIndicator(null);
		mExpandableListView.setDividerHeight(1);
		mExpandableListView.setDivider(getResources().getDrawable(R.drawable.expandable_listview_divider));
		mExpandableListView.setChildDivider(getResources().getDrawable(R.drawable.expandable_listview_divider));
		mExpandableListView.setAdapter(mExamExpandAdapter);

		// 保证只展开一个
		mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
			@Override
			public void onGroupExpand(int groupPosition) {
				for (int i = 0; i < mExpandableListView.getExpandableListAdapter().getGroupCount(); i++) {
					if (i != groupPosition) {
						mExpandableListView.collapseGroup(i);
					}
				}
			}
		});
		mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				mPopupWindow.dismiss();
				if (groupPosition == 0) {
					// 友盟统计
					MobclickAgent.onEvent(mContext, "readExam_filterItemClick");
					selectList(childPosition);
				} else if (groupPosition == 1) {
					if (childPosition == 0) {
						// 升序
						sortList(true);
					} else if (childPosition == 1) {
						// 降序
						sortList(false);
					}
				}
				listView.setSelection(0);
				mExamExpandAdapter.setSelectedIndex(groupPosition, childPosition);
				return true;
			}
		});
	}

	/**
	 * 
	 * @param 倒序或顺序flag为标识
	 *            true 为升序 false为倒序
	 */
	private void sortList(boolean flag) {
		if (mExamExpandAdapter != null && examDatas != null) {
			sortDatas.clear();
			sortDatas.addAll(examDatas);
			if (flag) {
				Collections.sort(sortDatas, new Comparator<ExamListDetail>() {
					@Override
					public int compare(ExamListDetail lhs, ExamListDetail rhs) {
						if (lhs.book.equals(rhs.book)) {
							return Integer.parseInt(lhs.task) - Integer.parseInt(rhs.task);
						} else {
							return Integer.parseInt(lhs.book) - Integer.parseInt(rhs.book);
						}
					}
				});
			} else {
				Collections.sort(sortDatas, new Comparator<ExamListDetail>() {
					@Override
					public int compare(ExamListDetail lhs, ExamListDetail rhs) {
						if (lhs.book.equals(rhs.book)) {
							return Integer.parseInt(lhs.task) - Integer.parseInt(rhs.task);
						} else {
							return Integer.parseInt(rhs.book) - Integer.parseInt(lhs.book);
						}
					}
				});
			}
			adapter.resetData(sortDatas);
		}
	}

	private void selectList(int position) {
		sortDatas.clear();
		for (int i = 0; i < examDatas.size(); i++) {
			if (examDatas.get(i).classify_id.equals(subjectDatas.get(position).classify_id)) {
				sortDatas.add(examDatas.get(i));
			}
		}
		adapter.resetData(sortDatas);
	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.iv_topbar_back:
			finish();
			break;
		case R.id.iv_topbar_right:
			openSelectorView();
			break;
		default:
			break;
		}
	}

	private void openSelectorView() {
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else if (mExamExpandAdapter.getGroupCount() > 0) {
			mPopupWindow.showAsDropDown(findViewById(R.id.topbar_container));
		}
	}

}
